#!/usr/bin/perl -w
use strict;
use Env qw(HOME);

my $topdir = shift @ARGV; # get the name of the directory as 1st argument

my $nameToIds = shift @ARGV || die "please provide the nameToPlateId file";
my $out = shift || "$topdir/index.html";

my $title = "N.crassa Cell Wall Phenotyping Screen";


open(my $fh => $nameToIds) || die "$nameToIds: $!";
my %lookup;
while(<$fh>) {
    chomp;
    my ($ncu,$plateid) = split(/,/,$_);
    $lookup{$ncu} = $plateid;
    $lookup{$plateid} = $ncu;
}

opendir(DIR,$topdir) || die $!;
my %genes;
my @subdirs;
for my $subdir ( readdir(DIR) ) {
    next if $subdir =~ /^\./; # skip hidden directories
    next unless -d "$topdir/$subdir"; # skip unless it is a directory
    push @subdirs,$subdir;
    opendir(SUBDIR,"$topdir/$subdir") || die $!;
    for my $file ( readdir(SUBDIR)) { # read files in the subdirectory
	next unless $file =~ /(\S+)\.jpg$/; # only process the .jpg files
	my $base = $1; # the basename of the file is everything before the .jpg
	if( my $gene = $lookup{$base} ) {
	    $genes{$gene}->{$subdir} = "$subdir/$file";
	} else {
	    warn("cannot find Gene ID for $base\n");
	}
    }
}
open(my $ofh => ">$out") || die $!;
print $ofh "<HTML><HEAD><TITLE>$title</TITLE>\n<BODY BGCOLOR=\"WHITE\">\n";

print $ofh "<TABLE ALIGN=\"left\" BORDER=\"2\">\n";
print $ofh "<TR><TH>GENE</TH><TH>PLATEID</TH>"; # print the table header
for my $subdir ( @subdirs ) {
    print $ofh "<TH>$subdir</TH>";
}
print $ofh "</TR>\n";

for my $gene ( sort keys %genes ) {
    print $ofh "<TR><TD><b><a href=\"http://fungidb.org/gene/NcraOR74A__$gene\" target=\"Broad\">$gene</a></b></TD><TD>$lookup{$gene}</TD>";
    for my $subdir ( @subdirs ) {
	printf $ofh "<TD><a href=\"%s\"><img width=200 src=\"%s\"/></a></TD> ",
	$genes{$gene}->{$subdir},$genes{$gene}->{$subdir};
    }
    print $ofh "</TR>\n";
}
print $ofh "</TABLE></BODY></HTML>\n";
